package br.com.bolsamovel;

import java.text.DecimalFormat;

import android.content.Context;
import android.graphics.Rect;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.AttributeSet;
import android.widget.EditText;

public class NumberEdit extends EditText {
	private String mask;
	
	public NumberEdit(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		setup(attrs);
	}

	public NumberEdit(Context context, AttributeSet attrs) {
		super(context, attrs);
		setup(attrs);
	}
	
	private void setup(AttributeSet aset ){
		mask = aset.getAttributeValue("http://schemas.android.com/apk/res/br.com.bolsamovel", "mask");
		
/*		setFilters(new InputFilter[]{ new InputFilter(){
			String valids = "0123456789,.";
			
			public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
				if(source.length() > 1){
					return null;
				}
				
				return valids.indexOf(source.toString()) > -1 ? null: "";
			}
			
		}});
*/		
	}

	public NumberEdit(Context context) {
		super(context);
	}
	
	protected void onFocusChanged (boolean gainFocus, int direction, Rect previouslyFocusedRect){
		try{
			if(!gainFocus){
				String t = getText().toString();
				setText(applyMask(t));
			}
		}catch (Exception e) {
		}
		
		super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
	}
	
	private String applyMask(String s){
		double d = StringUtils.normalizeAsNumber(s);
		
		if(mask != null && mask.length() > 0){
			DecimalFormat df = new DecimalFormat(mask);
			return df.format(d);
		}
		
		return String.valueOf(d);
	}
	
	public void initText(String s){
		String toSet = "";
		
		if(s != null && s.length() > 0){
			toSet = applyMask(s);
		}
		
		setText(toSet);
	}
}
